local skynet = require "skynet"
-- local snax = require "snax"
local socket = require "skynet.socket"
local ws_server = require "ws.ws_server"

local wsserver_port = skynet.getenv "wsserver_port"
wsserver_port = tonumber(wsserver_port)

local CMD = {}

local function close_fd(fd)
	local c = connection[fd]
	if c then
		c.agent = nil
		connection[fd] = nil
	end
end

local CMD = {}


function CMD.connect(fd, addr)

	local agent = skynet.newservice("wsagent", fd, addr,skynet.self())
	local c = {
		fd = fd,
		ip = addr,
		agent = agent
	}
	connection[fd] = c
end

function CMD.kick(source, fd)
	local c = connection[fd]
	if c then
		skynet.send(c.agent, "lua", "close")
		close_fd(fd)
	end
end




function CMD.start( conf )
	wsgate = conf.wsgate
end

skynet.start(function()		
	local config = mode
	skynet.error("ws start " .. wsserver_port)
	skynet.dispatch("lua", function(session, source, cmd,...)
		local f = assert(CMD[cmd])
		if f then
			skynet.ret(skynet.pack(f(...)))
		end
	end)

	local id = socket.listen("0.0.0.0",wsserver_port)
	-- print(id)
	socket.start(id, function(id2, addr)
		if wsgate then
			skynet.send(wsgate,"lua","connect", id2, addr)
		end
	end)
end)
